/*********************
* Author:Dzlua
* QQ:505544956
* time:2016/08/08
*/
#include "Cursor.h"
#include "../edui_sdl.h"

EDUI_NAMESPACE_BEGIN

#ifdef EDUI_TEST_NEW_DELETE
int Cursor::m_newdeleteNum = 0;
int Cursor::_GetNewDeleteNum()
{
    return m_newdeleteNum;
}
#endif

Cursor* Cursor::GetInterface()
{
    Cursor* cursor = new Cursor;
#ifdef EDUI_TEST_NEW_DELETE
    ++m_newdeleteNum;
    Log("[Cursor] new cursor %d", cursor);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Add("Cursor", cursor);
#endif
    return cursor;
}

void Cursor::Release()
{
#ifdef EDUI_TEST_NEW_DELETE
    --m_newdeleteNum;
    Log("[Cursor] delete cursor %d", this);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Remove(this);
#endif
    delete this;
}

Cursor* Cursor::ToCursor(ICursor* cursor)
{
    return dynamic_cast<Cursor*>(cursor);
}

Cursor::Cursor() : m_cursor(0)
{}

Cursor::~Cursor()
{
    this->Destroy();
}

bool Cursor::Create(const Uint8* data, const Uint8* mask, int w, int h, int hotX, int hotY, const char* name, int id)
{
    if (!name) return false;
    if (m_cursor) return false;
    m_cursor = SDL_CreateCursor(data, mask, w, h, hotX, hotY);
    if (!m_cursor) return false;

    CursorMgr* mgr = IEnginePtr->GetCursorMgr();
    if (!mgr->Add(name, this, id)){
        this->Destroy();
        return false;
    }

    return true;
}

bool Cursor::Create(ISurface* surface, int hotX, int hotY, const char* name, int id)
{
    if (!surface || !name) return false;
    if (m_cursor) return false;
    m_cursor = SDL_CreateColorCursor(Surface::ToSurface(surface)->GetSDLSurface(), hotX, hotY);
    if (!m_cursor) return false;

    CursorMgr* mgr = IEnginePtr->GetCursorMgr();
    if (!mgr->Add(name, this, id)){
        this->Destroy();
        return false;
    }

    return true;
}

bool Cursor::Create(SystemCursor sysid, const char* name, int id)
{
    if (m_cursor || !name) return false;
    m_cursor = SDL_CreateSystemCursor((SDL_SystemCursor)sysid);
    if (!m_cursor) return false;

    CursorMgr* mgr = IEnginePtr->GetCursorMgr();
    if (!mgr->Add(name, this, id)){
        this->Destroy();
        return false;
    }

    return true;
}

bool Cursor::Create(SDL_Cursor* cursor)
{
    if (this->IsOK()) return false;
    if (!cursor) return false;
    m_cursor = cursor;
    return true;
}

void Cursor::Destroy()
{
    if (m_cursor){
        SDL_FreeCursor(m_cursor);
    }
}

bool Cursor::IsOK()
{
    return (m_cursor != 0);
}

SDL_Cursor* Cursor::GetSDLCursor() const
{
    return m_cursor;
}

EDUI_NAMESPACE_END
